package com.diligreat.action; 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.diligreat.action.base.BaseAction;

/**  
 * @Author Bruce 
 * @Date 2012-10-23
 * @Comments
 */
public class FileUploadAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(FileUploadAction.class);
	private File file;
    private String fileFileName;
    private String fileFileContentType;

    private String message = "上传成功";
    
    private String fileNewName;
    
    //private static final String path = System.getProperty("user.dir") + "/upload/cover/";
    private static String path = "";//;

    public String execute() throws Exception {
        FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			//String path = this.getRequest().getRealPath("/upload/cover/");
			File f = this.getFile();
			    
			if(this.getFileFileName().endsWith(".exe")){
			    message="对不起,你上传的文件格式不允许!!!";
			    return ERROR;
			}else if(this.getFileFileName().toUpperCase().endsWith(".PDF")){
				path = ServletActionContext.getServletContext().getRealPath("/PDF/");
			}else {
				path = ServletActionContext.getServletContext().getRealPath("/upload/cover/");
			}
			fileNewName = System.currentTimeMillis() + this.getFileFileName().substring(this.getFileFileName().indexOf("."));
			logger.info("上传文件至："+path);
			inputStream = new FileInputStream(f);
			outputStream = new FileOutputStream(path + File.separator + fileNewName);
			byte[] buf = new byte[1024];
			int length = 0;
			while ((length = inputStream.read(buf)) != -1) {
			    outputStream.write(buf, 0, length);
			}
			
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(inputStream != null){
				inputStream.close();
			}
			 if(outputStream != null){
				 outputStream.close();
			 }
		    
		}
        
        return SUCCESS;
    }


	
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileFileContentType() {
		return fileFileContentType;
	}

	public void setFileFileContentType(String fileFileContentType) {
		this.fileFileContentType = fileFileContentType;
	}

	public String getMessage() {
		return message;
	}


	public String getFileNewName() {
		return fileNewName;
	}

    
}
 